/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package com.xxl.adapter.dao;

import cn.hutool.core.collection.CollectionUtil;
import com.xxl.adapter.core.XxlConvert;
import com.xxl.adapter.entity.JobLog;
import com.xxl.adapter.repository.JobLogRepository;
import com.xxl.job.admin.core.model.XxlJobLog;
import com.xxl.job.admin.dao.XxlJobLogDao;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaBuilder.In;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Component;

/**
 * XxlJobLogDaoImpl
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
@Slf4j
@Component
public class JobLogDaoImpl implements XxlJobLogDao, XxlConvert {

  @Autowired private JobLogRepository repository;

  public Page<JobLog> page(
      int offset,
      int pagesize,
      int jobGroup,
      int jobId,
      Date triggerTimeStart,
      Date triggerTimeEnd,
      int logStatus) {
    return repository.findAll(
        ((root, query, cb) -> {
          Predicate predicate = cb.conjunction();
          if (jobId == 0 && jobGroup > 0) {
            predicate.getExpressions().add(cb.equal(root.get("jobGroup"), jobGroup));
          }
          if (jobId > 0) {
            predicate.getExpressions().add(cb.equal(root.get("jobId"), jobId));
          }
          if (triggerTimeStart != null) {
            predicate
                .getExpressions()
                .add(cb.greaterThan(root.get("triggerTime"), triggerTimeStart));
          }
          if (triggerTimeEnd != null) {
            predicate.getExpressions().add(cb.lessThan(root.get("triggerTime"), triggerTimeEnd));
          }
          if (logStatus == 1) {
            predicate.getExpressions().add(cb.equal(root.get("handleCode"), 200));
          }
          if (logStatus == 2) {
            In<Integer> in1 = cb.in(root.get("triggerCode")), in2 = cb.in(root.get("handleCode"));
            CollectionUtil.newArrayList(0, 200)
                .forEach(
                    i -> {
                      in1.value(i);
                      in2.value(i);
                    });
            predicate.getExpressions().add(cb.and(cb.or(cb.not(in1), cb.not(in2))));
          }
          if (logStatus == 3) {
            predicate.getExpressions().add(cb.equal(root.get("triggerCode"), 200));
            predicate.getExpressions().add(cb.equal(root.get("handleCode"), 0));
          }

          return predicate;
        }),
        PageRequest.of(
            offset, pagesize, Sort.by(CollectionUtil.newArrayList(Order.desc("triggerTime")))));
  }

  @Override
  public List<XxlJobLog> pageList(
      int offset,
      int pagesize,
      int jobGroup,
      int jobId,
      Date triggerTimeStart,
      Date triggerTimeEnd,
      int logStatus) {
    Page<JobLog> page =
        this.page(offset, pagesize, jobGroup, jobId, triggerTimeStart, triggerTimeEnd, logStatus);

    return this.convert(XxlJobLog.class, page.getContent());
  }

  @Override
  public int pageListCount(
      int offset,
      int pagesize,
      int jobGroup,
      int jobId,
      Date triggerTimeStart,
      Date triggerTimeEnd,
      int logStatus) {
    Page<JobLog> page =
        this.page(offset, pagesize, jobGroup, jobId, triggerTimeStart, triggerTimeEnd, logStatus);
    return (int) page.getTotalElements();
  }

  @Override
  public XxlJobLog load(long id) {
    return this.convert(XxlJobLog.class, repository.findById(id).orElse(null));
  }

  @Override
  public long save(XxlJobLog xxlJobLog) {
    JobLog jobLog = repository.save(this.convert(JobLog.class, xxlJobLog));
    xxlJobLog.setId(jobLog.getId());
    return jobLog.getId();
  }

  @Override
  public int updateTriggerInfo(XxlJobLog xxlJobLog) {
    long id = xxlJobLog.getId();
    JobLog jobLog = repository.findById(id).orElse(null);
    if (jobLog != null) {
      jobLog.setTriggerTime(xxlJobLog.getTriggerTime());
      jobLog.setTriggerCode(xxlJobLog.getTriggerCode());
      jobLog.setTriggerMsg(xxlJobLog.getTriggerMsg());
      jobLog.setExecutorAddress(xxlJobLog.getExecutorAddress());
      jobLog.setExecutorHandler(xxlJobLog.getExecutorHandler());
      jobLog.setExecutorParam(xxlJobLog.getExecutorParam());
      jobLog.setExecutorShardingParam(xxlJobLog.getExecutorShardingParam());
      jobLog.setExecutorFailRetryCount(xxlJobLog.getExecutorFailRetryCount());

      repository.save(jobLog);
    }

    return (int) id;
  }

  @Override
  public int updateHandleInfo(XxlJobLog xxlJobLog) {
    long id = xxlJobLog.getId();
    JobLog jobLog = repository.findById(id).orElse(null);
    if (jobLog != null) {
      jobLog.setHandleTime(xxlJobLog.getHandleTime());
      jobLog.setHandleCode(xxlJobLog.getHandleCode());
      jobLog.setHandleMsg(xxlJobLog.getHandleMsg());

      repository.save(jobLog);
    }

    return (int) id;
  }

  @Override
  public int delete(int jobId) {
    List<JobLog> list = repository.findAll((root, query, cb) -> cb.equal(root.get("jobId"), jobId));
    if (CollectionUtil.isNotEmpty(list)) {
      repository.deleteAllInBatch(list);
    }

    return 1;
  }

  @Override
  public Map<String, Object> findLogReport(Date from, Date to) {
    return repository.findLogReport(from, to);
  }

  @Override
  public List<Long> findClearLogIds(
      int jobGroup, int jobId, Date clearBeforeTime, int clearBeforeNum, int pagesize) {
    List<Long> ids = new ArrayList<>();
    if (clearBeforeNum < 0) {
      repository
          .findAll(
              ((root, query, cb) -> buildWhere(jobGroup, jobId, root, cb)),
              PageRequest.of(0, clearBeforeNum, Sort.by(Order.desc("triggerTime"))))
          .getContent()
          .forEach(i -> ids.add(i.getId()));
    }

    Page<JobLog> page =
        repository.findAll(
            ((root, query, cb) -> {
              Predicate predicate = buildWhere(jobGroup, jobId, root, cb);
              if (clearBeforeTime != null) {
                predicate
                    .getExpressions()
                    .add(cb.lessThan(root.get("triggerTime"), clearBeforeTime));
              }
              if (clearBeforeNum > 0) {
                In<Long> in = cb.in(root.get("id"));
                ids.forEach(in::value);
                predicate.getExpressions().add(cb.in(in));
              }

              return predicate;
            }),
            PageRequest.of(0, pagesize));

    return page.getContent().stream().map(JobLog::getId).collect(Collectors.toList());
  }

  private Predicate buildWhere(int jobGroup, int jobId, Root<JobLog> root, CriteriaBuilder cb) {
    Predicate predicate = cb.conjunction();
    if (jobGroup > 0) {
      predicate.getExpressions().add(cb.equal(root.get("jobGroup"), jobGroup));
    }
    if (jobId > 0) {
      predicate.getExpressions().add(cb.equal(root.get("jobId"), jobId));
    }

    return predicate;
  }

  @Override
  public int clearLog(List<Long> logIds) {
    repository.deleteAllById(logIds);
    return 1;
  }

  @Override
  public List<Long> findFailJobLogIds(int pagesize) {
    return repository
        .findAll(
            (root, query, cb) -> {
              Predicate predicate = cb.conjunction();
              In<Integer> in = cb.in(root.get("triggerCode"));
              in.value(0);
              in.value(200);
              predicate
                  .getExpressions()
                  .add(cb.or(cb.not(in), cb.notEqual(root.get("handleCode"), 0)));
              predicate.getExpressions().add(cb.notEqual(root.get("handleCode"), 200));
              predicate.getExpressions().add(cb.equal(root.get("alarmStatus"), 0));

              return predicate;
            },
            PageRequest.of(0, pagesize, Sort.by(Order.asc("id"))))
        .getContent()
        .stream()
        .map(JobLog::getId)
        .collect(Collectors.toList());
  }

  @Override
  public int updateAlarmStatus(long logId, int oldAlarmStatus, int newAlarmStatus) {
    List<JobLog> list =
        repository.findAll(
            ((root, query, cb) ->
                cb.and(
                    cb.equal(root.get("id"), logId),
                    cb.equal(root.get("alarmStatus"), oldAlarmStatus))));
    if (CollectionUtil.isNotEmpty(list)) {
      list.forEach(i -> i.setAlarmStatus(newAlarmStatus));

      repository.saveAll(list);
    }

    return (int) logId;
  }

  @Override
  public List<Long> findLostJobIds(Date losedTime) {
    return repository.findLostJobIds(losedTime);
  }

  @Override
  public Logger getLogger() {
    return log;
  }
}
